package com.xiaov.android.games.my3d;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;

public class GameView extends GLSurfaceView implements Renderer {
	
	public static int width = 0; 
	public static int height = 0;
	
	GameThread gameThread = null;
	static SceneBase currentScene;
	
	private float fps = 0;
	private long lastTime = 0;
	
	public GameView(Context context) {
		super(context);
		width = getWidth();
		height = getHeight();
		SceneBase.context = context;
		
		this.setFocusable(true);
		setFocusableInTouchMode(true);
		
		setCurrentScene(new MenuScene());
		
		this.setRenderer(this);
		
		gameThread = new GameThread();
		gameThread.start();
	}
	
	public static void setCurrentScene(SceneBase current) {
		currentScene = current;
	}
	
	@Override
	public boolean onTouchEvent(final MotionEvent event) {
		// TODO Auto-generated method stub
		currentScene.onTouchEvent(event);
		return true;
	}
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		//super.onKeyDown(keyCode, event);
		return currentScene.onKeyDown(keyCode, event);
		//return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onDrawFrame(GL10 gl) {
		currentScene.onDrawFrame(gl);
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		this.width = width;
		this.height = height;
		currentScene.onSurfaceChanged(gl, width, height);
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		currentScene.onSurfaceCreated(gl, config);
	}
	
	class GameThread extends Thread
	{
		SurfaceHolder surfaceHolder;
		boolean run = true;
		
		public void run()
		{
			while(run)
    		{
    			try
    			{
    				long nowTime = System.currentTimeMillis();
    				//if(nowTime - lastTime > 40){
	    				fps = 1 * 1000 / (nowTime - lastTime);
						lastTime = nowTime;
						currentScene.tick();
						//Log.v("FPS:  ", "" + fps);
						requestRender();
    				//}
					
					sleep(20);
    			}
    			catch(Exception e)
    			{
    				e.printStackTrace();
    			}
    			finally
    			{
    				
    			}
    		} 
		}
	}
}
